package com.itheima.controller;

import com.itheima.pojo.JsonResult;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import jdk.nashorn.internal.ir.debug.ClassHistogramElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping(value = "/user",produces = "application/json;charset=utf-8")
public class UserController {


    @Autowired
    private UserService userService;

   @PostMapping ("/login")
   @ResponseBody
    public String login(String username, String password, HttpServletRequest request){
        List<User> list = userService.select();
        for (User user : list) {
            if (user.getUsername().equals(username)&&user.getPassword().equals(password)) {
                request.getSession().setAttribute("user", username);
                // request.setAttribute("user",username);
                return "登入成功";
            }
        }
        return "登入失败";
    }

    @PostMapping ("/add")
    @ResponseBody
    public JsonResult add(@RequestBody User user) {

        String pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pwd);


        boolean flag = userService.add(user);
        if (!flag){
            return JsonResult.error("添加失败");
        }
        return JsonResult.success(userService.add(user));
    }
    @GetMapping("/select")
    @ResponseBody
    public JsonResult selectAll(){
        return JsonResult.success(userService.select());
    }
    @PutMapping("/update")
    @ResponseBody
    public JsonResult updateById(@RequestBody User user){


            if (user.getPassword()!=null){
                return JsonResult.error("密码无法修改");
            }

        boolean flag = userService.update(user);
        if (!flag){
            return JsonResult.error("修改失败");
        }
        return JsonResult.success(userService.update(user));
    }
    @DeleteMapping("/delete")
    @ResponseBody
    public JsonResult delete(@RequestParam String id){
        boolean flag = userService.deleteById(id);
        if (!flag){
            return JsonResult.error("删除失败");
        }
        return JsonResult.success(userService.deleteById(id));
    }

}
